#define _CRT_SECURE_NO_WARNINGS 1
#include "Online Courses Selecting System.h"

//当前学生信息的打印学生信息的打印
void print(Student* pphead)
{
	assert(pphead);

	Student* pcur = pphead;
	while (pcur)
	{
		printf("%d %s %d %s %d %d\n", pcur->ID, pcur->name, pcur->CourseNum, pcur->CourseName, pcur->Hours, pcur->Score);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

//创建学生信息
Student* creat(int id, const char* name, int cnum, const char* cname, int hours, int score)
{
	Student* newnode = (Student*)malloc(sizeof(Student));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	newnode->CourseName = cname;
	newnode->CourseNum = cnum;
	newnode->Hours = hours;
	newnode->ID = id;
	newnode->name = name;
	newnode->Score = score;
	newnode->next = NULL;

	return newnode;
}

//学生信息的添加
void push(Student** pphead, int id, const char* name, int cnum, const char* cname, int hours, int score)
{
	assert(pphead);

	Student* newnode = creat(cnum, cname, hours, score, id, name);
	if (*pphead == NULL)
	{
		//空链表
		*pphead = newnode;
	}
	else
	{
		Student* ptail = *pphead;
		while (ptail->next != NULL)
		{
			ptail = ptail->next;
		}
		//走到这里，ptail指向尾节点
		ptail->next = newnode;
	}
}

//查找指定学生
Student* find(Student *pphead,int id)
{
	assert(pphead);

	Student* cur = pphead;
	while (cur)
	{
		if (cur->ID == id)
		{
			return cur;
		}
		cur = cur->next;
	}
	//走到这里，说明找不到该学生
	return NULL;
}

//指定学生信息的删除
void delete(Student** pphead,int id)
{
	assert(pphead && *pphead);

	//判断该学生是否存在
	if (find(*pphead, id))
	{
		if ((*pphead)->ID == id)
		{
			//说明要删除的学生信息是第一个节点
			Student* Next = (*pphead)->next;
			free(*pphead);
			*pphead = Next;
		}
		else
		{
			Student* prev = *pphead;
			while (prev->next->ID != id)
			{
				prev = prev->next;
			}
			//走到这里，说明prev就是要删除节点的前一个节点
			Student* del = prev->next;
			prev->next = prev->next->next;
			free(del);
			del = NULL;
		}
	}
	else
	{
		printf("该学生不存在！\n");
		exit(-1);
	}
}

//以学号查找某个学生
void FindByID(Student *pphead, int id)
{
	assert(pphead);

	Student* cur = pphead;
	if (cur = find(pphead,id))
	{
		printf("%d %s %d %s %d %d\n", cur->ID, cur->name, cur->CourseNum, cur->CourseName,
			cur->Hours, cur->Score);
	}
	else
	{
		printf("查无此人！\n");
	}
}

//保存学生信息
void Saveinformation(Student* pphead)
{
	//打开文件
	FILE* pf = fopen("studet.txt", "a");
	Student* cur = pphead;

	//将链表内容写到文件中
	while (cur)
	{
		fprintf(pf, "%d %s %d %s %d %d\n", cur->ID, cur->name, cur->CourseNum, cur->CourseName,
			cur->Hours, cur->Score);
		cur = cur->next;
	}

	//关闭文件
	fclose(pf);
	pf = NULL;
}


//链表的销毁
void Destroy(Student** pphead)
{
	Student* cur = *pphead;
	Student* next = *pphead;
	while (cur)
	{
		next = next->next;
		free(cur);
		cur = next;
	}
	*pphead = NULL;
}


//已经保存了的学生信息的打印
void Browse()
{
	char string[50] = {0};
	//打开文件
	FILE* pf = fopen("studet.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		exit(-1);
	}

	//读取信息，并打印在屏幕上
	while (fgets(string, 50, pf))
	{
		printf("%s", string);
	}

	fclose(pf);
	pf = NULL;
}